const WebSocket = require('ws')
const path = require('path')
const fileUtils = require('../util/file_utils')

const wss = new WebSocket.Server({
  port: 9998
})

module.exports.listen = () => {
  wss.on('connection', client => {

    client.on('message', async msg => {
      const payload = JSON.parse(msg)
      const action = payload.action
      if (action === 'getData') {
        // trend,seller,map,stock,hot,rank
        let filePath = path.join(__dirname, `../data/${payload.chartName}.json`)
        payload.data = await fileUtils.getData(filePath)
        client.send(JSON.stringify(payload))
      } else {
        wss.clients.forEach(client => client.send(JSON.stringify(payload)))
      }
    })
  })
}